﻿using System;
using System.Web;
using Turquoise.Core.Entities;
using Turquoise.Helpers;
using Turquoise.Web.Common.Abstract;

namespace Turquoise.Web.Common.Security
{
    public class WebSecurityManager : IWebSecurityManager
    {
        public void Set(TurquoiseIdentity identity, DateTime expirationDateTime, string key, bool rememberMe)
        {
            var serializedIdentity = SerializationHelper.SerializeToString(identity);
            var encryptedSerializedIdentity = SecurityHelper.Encrypt(serializedIdentity);
            HttpContext.Current.Response.Cookies.Add(new HttpCookie(key, encryptedSerializedIdentity)
            {
                Expires = expirationDateTime
            });
        }
        public TurquoisePrincipal Get(string key)
        {
            var cookie = HttpContext.Current.Request.Cookies[key];
            var value = cookie?.Value;
            if (string.IsNullOrEmpty(value)) return null;
            var decryptedValue = SecurityHelper.Decrypt(value);
            var identity = SerializationHelper.DeserializeFromString<TurquoiseIdentity>(decryptedValue);
            var principle = new TurquoisePrincipal(identity);
            return principle;
        }
        public void Remove(string key)
        {
            var cookie = HttpContext.Current.Request.Cookies[key];
            HttpContext.Current.Response.Cookies.Remove(key);
            if (cookie == null) return;
            cookie.Expires = DateTime.Now.AddDays(-10);
            cookie.Value = null;
            HttpContext.Current.Response.SetCookie(cookie);
        }
    }
}
